﻿using Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WxPayAPI
{
    /// <summary>
    /// 支付结果通知回调处理类
    /// 负责接收微信支付后台发送的支付结果并对订单有效性进行验证，将验证结果反馈给微信支付后台
    /// </summary>
    public class ResultNotify:Notify
    {
        public ResultNotify(Page page):base(page)
        {
        }

        public override void ProcessNotify()
        {
            WxPayData notifyData = GetNotifyData();
            

            //检查支付结果中transaction_id是否存在
            if (!notifyData.IsSet("transaction_id"))
            {
                //若transaction_id不存在，则立即返回结果给微信支付后台
                WxPayData res = new WxPayData();
                res.SetValue("return_code", "FAIL");
                res.SetValue("return_msg", "支付结果中微信订单号不存在");
                Log.Error(this.GetType().ToString(), "The Pay result is error : " + res.ToXml());
                page.Response.Write(res.ToXml());
                page.Response.End();
            }

            string transaction_id = notifyData.GetValue("transaction_id").ToString();
            page.Response.Write("<script>alert("+ transaction_id + ")</script>");
            //查询订单，判断订单真实性
            if (!QueryOrder(transaction_id))
            {
                //若订单查询失败，则立即返回结果给微信支付后台
                WxPayData res = new WxPayData();
                res.SetValue("return_code", "FAIL");
                res.SetValue("return_msg", "订单查询失败");
                Log.Error(this.GetType().ToString(), "Order query failure : " + res.ToXml());
                page.Response.Write(res.ToXml());
                page.Response.End();
            }
            //查询订单成功
            else
            {
                WxPayData res = new WxPayData();
                res.SetValue("return_code", "SUCCESS");
                res.SetValue("return_msg", "OK");
                Log.Info(this.GetType().ToString(), "order query success : " + res.ToXml());
                page.Response.Write(res.ToXml());

                string out_trade_no = notifyData.GetValue("out_trade_no").ToString();
                string openid = notifyData.GetValue("openid").ToString();
          
                var orderid = int.Parse(notifyData.GetValue("attach").ToString());
                var ordType = notifyData.GetValue("out_trade_no").ToString().Substring(0, 2);
                var xtType = out_trade_no.Substring(out_trade_no.Length - 2, 2);
                string total_fee = notifyData.GetValue("total_fee").ToString();
                
                Entities db = new Entities();
                if (ordType.ToUpper() == "CZ")//充值
                {

                    U_CZ mycz = new U_CZ();

                    var mydb = db.U_CZ.SingleOrDefault(p => p.UShareGuid == out_trade_no);

                    if (mydb == null)
                    { 
                        U_CZ mybm = new U_CZ();
                   mybm.UGuid = openid;//享受分红人
         

                    decimal myzc = Convert.ToDecimal(total_fee) / 100;
                        //if(myzc=1000)
                     mybm.CZMoney = myzc;



                    mybm.CZTime = DateTime.Now;
                    mybm.CZPayType = "充值";
                    mybm.CZstat = 0;
                        mybm.UShareGuid = out_trade_no;
                    db.U_CZ.Add(mybm);
                    db.SaveChanges();
                    }

                    mydb.CZstat = 1;



                }
                if (ordType.ToUpper() == "SO")//购买
                {
                    var mydb = db.S_Order.Where(x => x.OParentId == orderid || x.OrderID == orderid);//全部
                    foreach (var yorder in mydb)
                    {
                        yorder.OState = 1;
                       
                        yorder.OpayType = "微信";
                     
                        yorder.transaction_id = transaction_id;
                        yorder.out_trade_no = out_trade_no;

                        if (yorder.OPayState != 1)
                        {
                            yorder.OpayTime = DateTime.Now;
                            yorder.OPayState = 1;
                        }

                        if (yorder.OParentId==0)
                        {

                            var user = db.User.SingleOrDefault(p => p.UOpenID == yorder.UGUID);

                            if (user.Ustate < 1)
                            {
                                user.Ustate = 1;
                            }

                        }


                        db.SaveChanges();
                    }

                }
                if (ordType.ToUpper() == "SP")//商品
                {
                    if (xtType == "SS")
                    {
                      
                        var mydb = db.S_Order.Where(x => x.OParentId == orderid || x.OrderID == orderid);//全部
                        foreach (var yorder in mydb)
                        {
                            yorder.OState = 1;
                            yorder.OPayState = 1;
                            yorder.OpayType = "微信提货";
                            yorder.OpayTime = DateTime.Now;
                            yorder.transaction_id = transaction_id;
                            yorder.out_trade_no = out_trade_no;
                            db.SaveChanges();

                        }
                      
                    }
                 

                    //    var user=db.User.SingleOrDefault(p => p.UOpenID == mydb.OopenID);
                    //   user.Ustate = 2;

                    //      methods.giveProfitToMachineOwner(mydb.OrderID, mydb.OopenID);//给机柜住五星分润
                    //  methods.giveOneRMBToFirstMachineOwner(mydb.OrderID, mydb.OopenID);//给购买者级线中的第一个机柜住1元收益

                    // if(xx != 1)
                    // ycyy.giveProfitToParents(mydb.OrderID, mydb.OopenID);//给上级五星分润

                }

                if (ordType.ToUpper() == "DD")//商品
                {
                    if (xtType == "DD")
                    {
                        var mydb = db.S_DinDan.Where(x => x.OParentId == orderid || x.DingDdanID == orderid);//全部
                        foreach (var yorder in mydb)
                        {
                            yorder.OState = 1;
                            yorder.OPayState = 1;
                            yorder.OpayType = "微信零售";
                            yorder.OpayTime = DateTime.Now;
                            yorder.transaction_id = transaction_id;
                            yorder.out_trade_no = out_trade_no;
                            db.SaveChanges();

                        }


                    }
                }



                if (ordType.ToUpper() == "TZ")//签到（续费,投资）
                {
                    var mydb = db.U_TZ.SingleOrDefault(p => p.TZID == orderid);
                    mydb.TZstat = 1;
                }

                db.SaveChanges();
                page.Response.End();
            }
        }

        //查询订单
        private bool QueryOrder(string transaction_id)
        {
            WxPayData req = new WxPayData();
            req.SetValue("transaction_id", transaction_id);
            WxPayData res = WxPayApi.OrderQuery(req);
            if (res.GetValue("return_code").ToString() == "SUCCESS" &&
                res.GetValue("result_code").ToString() == "SUCCESS")
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}